// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  if (event.tag == 'selectUser') {
    return  await db.collection('user').where({
      _openid: wxContext.OPENID,
    }).count().then(res => {
      console.log(res.total);
      if (!res.total) { //用户没有注册过，进行注册
        return new Promise((resolve,reject)=>{
          db.collection('user').add({
            data:{
              _openid: wxContext.OPENID,
              integral:0,
              _greateTime:db.serverDate(),
              _updateTime:db.serverDate()
            }
          }).then(()=>{
            resolve(wxContext.OPENID) //注册成功，返回openid
          })
        })
        
      }else{//注册过，返回openid
        return wxContext.OPENID
      }
    })
   

  }

  // return {
  //   event,
  //   openid: wxContext.OPENID,
  //   appid: wxContext.APPID,
  //   unionid: wxContext.UNIONID,
  // }
}